<template>
  <div class="received-questions-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <button @click="goBack" class="back-btn">← 返回管理中心</button>
        <h1 class="page-title">别人共享给我的试题</h1>
        <p class="page-subtitle">查看他人分享给您的试题</p>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <div class="container">
        <!-- 搜索区域 -->
        <div class="search-section">
          <div class="search-row">
            <div class="form-group">
              <label>程序类型</label>
              <select v-model="searchForm.type" class="form-select">
                <option value="">全部</option>
                <option value="C++">C++</option>
                <option value="Python">Python</option>
                <option value="Java">Java</option>
                <option value="GOC">GOC</option>
              </select>
            </div>
            
            <div class="form-group">
              <label>题号</label>
              <input 
                v-model="searchForm.questionId" 
                type="text" 
                placeholder="请输入题号"
                class="form-input"
              />
            </div>
            
            <div class="form-group">
              <label>标题</label>
              <input 
                v-model="searchForm.title" 
                type="text" 
                placeholder="请输入关键词"
                class="form-input"
              />
            </div>
            
            <button @click="searchQuestions" class="search-btn">搜索</button>
          </div>
        </div>

        <!-- 试题列表标题 -->
        <div class="list-header">
          <h2 class="list-title">别人共享给我的试题列表</h2>
        </div>

        <!-- 试题表格 -->
        <div class="table-container">
          <table class="questions-table">
            <thead>
              <tr>
                <th>题号</th>
                <th>试题类型</th>
                <th>标题</th>
                <th>共享时间</th>
                <th>共享人</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="loading">
                <td colspan="6" class="loading-row">
                  <div class="loading-content">
                    <i class="fas fa-spinner fa-spin"></i>
                    正在加载别人共享给我的试题...
                  </div>
                </td>
              </tr>
              <tr v-else-if="questions.length === 0">
                <td colspan="6" class="empty-row">
                  <div class="empty-content">
                    <i class="fas fa-inbox"></i>
                    暂无别人共享给您的试题
                  </div>
                </td>
              </tr>
              <tr v-for="question in questions" :key="question.id" class="table-row">
                <td>{{ question.questionId }}</td>
                <td>{{ question.type }}</td>
                <td class="title-cell">{{ question.title }}</td>
                <td>{{ formatDate(question.shareTime) }}</td>
                <td>{{ question.sharedBy }}</td>
                <td class="action-cell">
                  <button @click="viewQuestion(question)" class="action-btn view-btn">查看</button>
                  <button @click="removeFromReceived(question)" class="action-btn remove-btn">移除</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <div class="pagination">
            <span class="page-info">(共 {{ totalCount }} 条)</span>
            <button 
              @click="goToPage(currentPage - 1)"
              :disabled="currentPage <= 1"
              class="page-btn"
            >
              上一页
            </button>
            <span class="current-page">{{ currentPage }}</span>
            <button 
              @click="goToPage(currentPage + 1)"
              :disabled="currentPage >= totalPages"
              class="page-btn"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { getReceivedQuestions, getTestQuestionById } from '@/api/testQuestion'
import { useRouter } from 'vue-router'
import logger from '../utils/logger.js'

export default {
  name: 'ReceivedQuestions',
  setup() {
    // Vue Router
    const router = useRouter()
    
    // 响应式数据
    const questions = ref([])
    const currentPage = ref(1)
    const totalPages = ref(1)
    const totalCount = ref(0)
    const pageSize = 10
    const loading = ref(false)

    // 搜索表单
    const searchForm = reactive({
      type: '',
      questionId: '',
      title: ''
    })

    // 数据已通过API获取，不再需要模拟数据

    // 方法
    const loadQuestions = async () => {
      if (loading.value) return // 防止重复加载
      
      loading.value = true
      try {
        logger.log('📨 [ReceivedQuestions] 加载别人共享给我的试题...')
        logger.log('📋 [ReceivedQuestions] 当前页:', currentPage.value)
        logger.log('📋 [ReceivedQuestions] 页大小:', pageSize)
        
        // 构建API参数
        const apiParams = {
          current: currentPage.value,
          size: pageSize,
          ...searchForm
        }
        
        logger.log('📡 [ReceivedQuestions] 调用API参数:', apiParams)
        
        // 调用API获取别人分享给我的试题数据
        const response = await getReceivedQuestions(apiParams)
        logger.log('✅ [ReceivedQuestions] API响应:', response)
        
        if (response && response.data) {
          const { data: responseData } = response
          
          if (responseData.code === 0 && responseData.data) {
            const { records, total, current, pages } = responseData.data
            
            // 更新题目列表
            questions.value = records || []
            totalCount.value = total || 0
            totalPages.value = pages || 1
            currentPage.value = current || 1
            
            logger.log('📊 [ReceivedQuestions] 加载成功:', {
              题目数量: questions.value.length,
              总数: totalCount.value,
              当前页: currentPage.value,
              总页数: totalPages.value
            })
          } else {
            throw new Error(responseData.message || '获取数据失败')
          }
        } else {
          throw new Error('API响应格式异常')
        }
        
      } catch (error) {
        logger.error('❌ [ReceivedQuestions] 加载试题失败:', error)
        
        // 显示错误信息
        if (window.alert) {
          alert('加载试题失败：' + (error.message || '网络错误'))
        }
        
        // 使用空数据作为后备
        questions.value = []
        totalCount.value = 0
        totalPages.value = 1
        currentPage.value = 1
      } finally {
        loading.value = false
      }
    }

    const searchQuestions = async () => {
      logger.log('🔍 [ReceivedQuestions] 执行搜索，参数:', searchForm)
      // 重置到第一页
      currentPage.value = 1
      // 重新加载数据
      await loadQuestions()
    }

    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false })
    }

    const goToPage = async (page) => {
      if (page >= 1 && page <= totalPages.value) {
        currentPage.value = page
        await loadQuestions()
      }
    }

    const viewQuestion = async (question) => {
      logger.log('👀 [ReceivedQuestions] 查看试题:', question)
      logger.log('🆔 [ReceivedQuestions] 题目ID:', question.questionId || question.id)
      
      try {
        // 获取题目ID
        const questionId = question.questionId || question.id
        
        if (!questionId) {
          logger.error('❌ [ReceivedQuestions] 题目ID不存在')
          alert('题目ID不存在，无法查看详情')
          return
        }
        
        logger.log('🌐 [ReceivedQuestions] 调用题目详情接口: /goc/testQuestion/findById')
        logger.log('📋 [ReceivedQuestions] 请求参数: { id:', questionId, '}')
        
        // 调用接口获取题目详情
        const response = await getTestQuestionById(questionId)
        
        logger.log('✅ [ReceivedQuestions] 题目详情API响应:', response)
        
        if (response && response.code === 0 && response.data) {
          const questionDetail = response.data
          logger.log('📦 [ReceivedQuestions] 题目详细数据:', questionDetail)
          
          // 更新当前题目的数据
          const questionIndex = questions.value.findIndex(q => 
            (q.questionId || q.id) === questionId
          )
          
          if (questionIndex !== -1) {
            // 合并详细数据到现有题目对象
            questions.value[questionIndex] = {
              ...questions.value[questionIndex],
              ...questionDetail,
              // 保留原有的共享相关信息
              shareTime: questions.value[questionIndex].shareTime,
              sharedBy: questions.value[questionIndex].sharedBy
            }
            logger.log('✅ [ReceivedQuestions] 题目数据已更新:', questions.value[questionIndex])
          }
          
          // 跳转到题目详情页
          router.push(`/problem/${questionId}`)
        } else {
          throw new Error(response?.message || '获取题目详情失败')
        }
        
      } catch (error) {
        logger.error('❌ [ReceivedQuestions] 查看题目详情失败:', error)
        alert('加载题目详情失败：' + (error.message || '网络错误'))
      }
    }

    const copyQuestion = (question) => {
      if (confirm(`确定要将试题"${question.title}"复制到您的试题库吗？`)) {
        logger.log('复制试题到我的试题:', question)
        // 执行复制逻辑
        // 调用API将试题复制到用户的试题库
        alert('试题已成功复制到您的试题库！')
      }
    }

    const removeFromReceived = (question) => {
      if (confirm(`确定要从接收列表中移除试题"${question.title}"吗？移除后将不再显示此试题。`)) {
        logger.log('移除接收的试题:', question)
        // 执行移除逻辑
        loadQuestions()
      }
    }

    const goBack = () => {
      // 返回管理中心
      window.history.back()
    }

    // 生命周期
    onMounted(() => {
      loadQuestions()
    })

    return {
      questions,
      currentPage,
      totalPages,
      totalCount,
      loading,
      searchForm,
      searchQuestions,
      formatDate,
      goToPage,
      viewQuestion,
      copyQuestion,
      removeFromReceived,
      goBack
    }
  }
}
</script>

<style scoped>
.received-questions-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

/* 页面头部样式 */
.page-header {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  padding: 30px;
  margin-bottom: 30px;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
}

.back-btn {
  background: #3498db;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  margin-bottom: 20px;
  transition: background 0.2s;
}

.back-btn:hover {
  background: #2980b9;
}

.page-title {
  font-size: 32px;
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-weight: 700;
}

.page-subtitle {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0;
}

/* 主要内容区域 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
}

.container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  padding: 30px;
}

/* 搜索区域 */
.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-row {
  display: flex;
  gap: 20px;
  align-items: end;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-select,
.form-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 150px;
}

.search-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 8px 24px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  height: 36px;
}

.search-btn:hover {
  background: #45a049;
}

/* 列表标题 */
.list-header {
  margin: 20px 0;
}

.list-title {
  font-size: 18px;
  color: #333;
  margin: 0;
  padding-left: 8px;
  border-left: 4px solid #4CAF50;
}

/* 表格样式 */
.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.questions-table {
  width: 100%;
  border-collapse: collapse;
}

.questions-table th {
  background: #4CAF50;
  color: white;
  padding: 15px 20px;
  text-align: left;
  font-weight: 500;
  font-size: 14px;
}

.questions-table td {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
  color: #333;
}

.table-row:hover {
  background: #f9f9f9;
}

.title-cell {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.action-cell {
  white-space: nowrap;
}

.action-btn {
  padding: 4px 12px;
  margin: 0 2px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.view-btn {
  background: #2196F3;
  color: white;
}

.copy-btn {
  background: #4CAF50;
  color: white;
}

.remove-btn {
  background: #FF9800;
  color: white;
}

.action-btn:hover {
  opacity: 0.8;
}

.loading-row,
.empty-row {
  text-align: center;
  padding: 40px 20px;
  font-size: 16px;
}

.loading-content {
  color: #3498db;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.loading-content i {
  font-size: 18px;
}

.empty-content {
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.empty-content i {
  font-size: 20px;
  color: #bdc3c7;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 10px;
  background: white;
  padding: 10px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.page-info {
  color: #666;
  font-size: 14px;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
}

.page-btn:hover:not(:disabled) {
  background: #f5f5f5;
}

.page-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
}

.current-page {
  background: #4CAF50;
  color: white;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  min-width: 32px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .received-questions-page {
    padding: 10px;
  }
  
  .page-header {
    padding: 20px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .container {
    padding: 20px;
  }
  
  .search-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .questions-table {
    font-size: 12px;
  }
  
  .questions-table th,
  .questions-table td {
    padding: 10px;
  }
}
</style> 